<template>
  <el-card>
    <BreadCrumb />
    <el-alert
      title="点击第一列可查看专业对应的班级"
      type="info"
      center
      :closable="false"
      show-icon
    />
    <el-table
      :data="majorClassList"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      style="width: 100%"
      stripe
      border
      highlight-current-row
    >
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-col
            v-for="item in scope.row.children"
            :key="item.id"
            :span="2"
          >
            <el-tag
              closable
              :disable-transitions="false"
              @close="handleTagClose(scope.row.id,item.id)"
            >
              {{ item.className }}
            </el-tag>
          </el-col>
          <el-col :span="2">
            <el-input
              v-if="inputVisible"
              ref="saveTagInput"
              v-model="inputValue"
              class="input-new-tag"
              size="small"
              @keyup.enter.native="handleInputConfirm(scope.row.id)"
            />
            <el-button v-else class="button-new-tag" size="small" type="success" plain @click="showInput">
              添加班级
            </el-button>
          </el-col>
        </template>
      </el-table-column>
      <el-table-column label="专业排序" min-width="33%">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span style="margin-left: 10px">{{ scope.row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="专业名称" min-width="33%">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span style="margin-left: 10px">{{ scope.row.majorName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="33%">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="danger"
            @click="deleteMajor(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script>
import BreadCrumb from '@/components/BreadCrumb'
import { isConfirm } from '@/utils/confirm'
import { checkAuth } from '@/utils/checkAuth'
import { getClassList, addClass, deleteClass } from '@/api/classApi'
import { getMajorList, deleteMajor } from '@/api/majorApi'
export default {
  components: {
    BreadCrumb
  },
  data() {
    return {
      // 专业班级列表数据
      majorClassList: [],
      // 动态生成 Tag 标签
      // 控制 input 输入框的显示与隐藏
      inputVisible: false,
      // input 输入框绑定的值
      inputValue: '',
      // 添加班级的表单信息
      addClassForm: {
        majorId: '',
        className: ''
      }
    }
  },
  created() {
    // 获取专业班级混合列表数据
    this.getMajorClassList()
  },
  methods: {
    // 获取班级，专业数据，并将其一一对应，用作 table 的数据
    async getMajorClassList() {
      this.majorClassList = []
      // 获取专业数据
      const { data: res1 } = await getMajorList()
      // 获取班级数据
      const { data: res2 } = await getClassList()
      res1.items.forEach(major => {
        const item = {
          id: major.id,
          sort: major.sort,
          majorName: major.majorName
        }
        const childrenList = []
        res2.items.forEach(cl => {
          if (major.majorName === cl.majorName) {
            const children = {
              id: cl.id,
              className: cl.className
            }
            childrenList.push(children)
          }
        })
        item.children = childrenList
        this.majorClassList.push(item)
      })
    },
    // 动态生成 Tag 标签
    async showInput() {
      if (!await checkAuth('添加班级')) return
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 点击按钮添加班级
    async handleInputConfirm(majorId) {
      const className = this.inputValue
      if (/^[0-9]+$/.test(className)) {
        // 发送请求添加班级
        this.addClassForm.majorId = majorId
        this.addClassForm.className = className
        const { data: res } = await addClass(this.addClassForm)
        this.addClassForm = res.class
        // 找到添加的专业
        this.majorClassList.forEach(item => {
          if (item.id === majorId) {
            item.children.push(this.addClassForm)
            this.$message.success('添加成功')
            this.inputVisible = false
            this.inputValue = ''
            return
          }
        })
      } else {
        // 不是数字类型
        this.$message.error('添加班级必须为数字')
      }
    },
    // 点击 x 删除班级
    async handleTagClose(majorId, classId) {
      if (!await checkAuth('删除班级')) return
      // 删除确认
      if (await isConfirm('此操作将永久删除该班级，是否继续？')) {
        // 网络请求删除班级
        await deleteClass(classId)
        // 本地删除班级
        // 找到删除的专业
        this.majorClassList.forEach(item => {
          if (item.id === majorId) {
            for (let i = 0; i < item.children.length; i++) {
              if (item.children[i].id === classId) {
                item.children.splice(i, 1)
                this.$message.success('删除成功')
                return
              }
            }
          }
        })
      }
    },
    // 删除专业
    async deleteMajor(major) {
      if (!await checkAuth('删除专业')) return
      // 判断该专业下是否有班级
      if (major.children.length > 0) {
        this.$message.error('该专业下存在班级，无法删除！')
        return
      }
      // 确认操作
      if (await isConfirm('此操作将永久删除该专业，是否继续？')) {
        // 发送网络请求，进行删除
        await deleteMajor(major.id)
        this.$message.success('删除成功')
        // 重新获取数据
        this.getMajorClassList()
      }
    }
  }
}
</script>

<style scoped>
.el-card{
  min-height:95%;
}
.el-table{
  font-size: 16px;
}
.el-table__row span {
  margin-left: 10px
}
.el-tag {
  margin: 7px 20px;
}
.button-new-tag {
  margin: 7px 0px 7px 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin: 7px 0px 7px 10px;
  vertical-align: bottom;
}
</style>
